﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 版权所有 (c) 2022 北京超维景生物科技有限公司 保留所有权利。
 * CLR版本：4.0.30319.42000
 * 文件名：Kernel
 * 
 * 创建者：huangyang
 * 电子邮箱：huangyang@tvscope.cn
 * 创建时间：2023/2/15 16:40:08
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;
using ImageK.Measure;
using ImageK.Plugin.Filter;

namespace ImageK.Text
{
    /// <summary>
    /// Uses a TextPanel to displays text in a window.
    /// </summary>
    public class TextWindow:Form
    {
        public const string LOC_KEY = "results.loc";
        public const string WIDTH_KEY = "results.width";
        public const string HEIGHT_KEY = "results.height";
        public const string LOG_LOC_KEY = "log.loc";
        public const string LOG_WIDTH_KEY = "log.width";
        public const string LOG_HEIGHT_KEY = "log.height";
        public const string DEBUG_LOC_KEY = "debug.loc";
        const string FONT_SIZE = "tw.font.size";
        const string FONT_ANTI= "tw.font.anti";
        TextPanel textPanel;
        // CheckboxMenuItem antialiased;
        int[] sizes = { 9, 10, 11, 12, 13, 14, 16, 18, 20, 24, 36, 48, 60, 72 };
        private int fontSize = 5; //(int)Prefs.get(FONT_SIZE, 5);
        MenuStrip mb;
        private static Font font;
        private bool isResultsTable;

        /**
        * Opens a new single-column text window.
        * @param title	the title of the window
        * @param text		the text initially displayed in the window
        * @param width	the width of the window in pixels
        * @param height	the height of the window in pixels
        */
        public TextWindow(string title, string text, int width, int height) : this(title, "", text, width, height)
        {
           
        }

        /**
        * Opens a new multi-column text window.
        * @param title	title of the window
        * @param headings	the tab-delimited column headings
        * @param text		text initially displayed in the window
        * @param width	width of the window in pixels
        * @param height	height of the window in pixels
        */
        public TextWindow(string title, string headings, string text, int width, int height)
        {
            Text = title;
            textPanel = new TextPanel(title);
            textPanel.setColumnHeadings(headings);
            if (text != null && !text.Equals(""))
                textPanel.append(text);
            create(title, textPanel, width, height);
        }

        /**
        * Opens a new multi-column text window.
        * @param title	title of the window
        * @param headings	tab-delimited column headings
        * @param text		ArrayList containing the text to be displayed in the window
        * @param width	width of the window in pixels
        * @param height	height of the window in pixels
        */
        public TextWindow(string title, string headings, ArrayList text, int width, int height)
        {
            this.Text = title;
            textPanel = new TextPanel(title);
            textPanel.setColumnHeadings(headings);
            if (text != null)
                textPanel.append(text);
            create(title, textPanel, width, height);
        }

		private void create(string title, TextPanel textPanel, int width, int height)
		{
			// enableEvents(AWTEvent.WINDOW_EVENT_MASK);
			// if (IJ.isLinux()) setBackground(ImageJ.backgroundColor);

			//添加textPanel控价
			// add("Center", textPanel);
            textPanel.Name = "Center";
            textPanel.Dock = DockStyle.Fill;
			this.Controls.Add(textPanel);

			// addKeyListener(textPanel);
			ImageK ij = IJ.GetInstance();
			if (ij != null)
			{
				// textPanel.addKeyListener(ij);
				// if (!IJ.isMacOSX())
				// {
				// 	Image img = ij.getIconImage();
				// 	if (img != null)
				// 		try { setIconImage(img); } catch (Exception e) { }
				// }
			}
			// addFocusListener(this);
			string title2 = this.Text;
			isResultsTable = title2.Equals("Results");
			if (!isResultsTable && title2.EndsWith("(Results)"))
			{
				isResultsTable = true;
				title2 = title2.Substring(0, title2.Length - 9);
				this.Text = title2;
				textPanel.title = title2;
			}
			//添加菜单
			addMenuBar();
			setFont();
			WindowManager.addWindow(this);
			Point loc = Point.Empty;
			int w = 0, h = 0;
			if (title.Equals("Results"))
			{
				// loc = Prefs.getLocation(LOC_KEY);
				// w = (int)Prefs.get(WIDTH_KEY, 0.0);
				// h = (int)Prefs.get(HEIGHT_KEY, 0.0);
                w = 600;
                h = 400;
            }
			else if (title.Equals("Log"))
			{
				// loc = Prefs.getLocation(LOG_LOC_KEY);
				// w = (int)Prefs.get(LOG_WIDTH_KEY, 0.0);
				// h = (int)Prefs.get(LOG_HEIGHT_KEY, 0.0);
			}
			else if (title.Equals("Debug"))
			{
				// loc = Prefs.getLocation(DEBUG_LOC_KEY);
				// w = width;
				// h = height;
			}
			if (loc != null && w > 0 && h > 0)
            {
                this.Width = w;
                this.Height = h;
                this.Location = loc;
            }
			else
			{
                this.Width = width;
                this.Height = height;
                if (!IJ.debugMode)
                {
                    this.StartPosition = FormStartPosition.CenterScreen;
                }
			}
			this.Show();
			WindowManager.setWindow(this);
		}

		/**
		* Opens a new text window containing the contents of a text file.
		* @param path		the path to the text file
		* @param width	the width of the window in pixels
		* @param height	the height of the window in pixels
		*/
		// public TextWindow(String path, int width, int height)
		// {
		// 	Text ="";
		// 	enableEvents(AWTEvent.WINDOW_EVENT_MASK);
		// 	textPanel = new TextPanel();
		// 	textPanel.addKeyListener(IJ.getInstance());
		// 	add("Center", textPanel);
		// 	if (openFile(path))
		// 	{
		// 		WindowManager.addWindow(this);
		// 		setSize(width, height);
		// 		show();
		// 		WindowManager.setWindow(this);
		// 	}
		// 	else
		// 		dispose();
		// }

		void addMenuBar()
		{
			mb = new MenuStrip();
			// if (Menus.getFontSize() != 0)
			// 	mb.setFont(Menus.getFont());
            ToolStripMenuItem m = new ToolStripMenuItem("File");
			// m.add(new MenuItem("Save As...", new MenuShortcut(KeyEvent.VK_S)));
			// if (isResultsTable)
			// {
			// 	m.add(new MenuItem("Rename..."));
			// 	m.add(new MenuItem("Duplicate..."));
			// }
			// m.addActionListener(this);
			mb.Items.Add(m);
			// textPanel.fileMenu = m;
			// m = new Menu("Edit");
			// m.add(new MenuItem("Cut", new MenuShortcut(KeyEvent.VK_X)));
			// m.add(new MenuItem("Copy", new MenuShortcut(KeyEvent.VK_C)));
			// m.add(new MenuItem("Clear"));
			// m.add(new MenuItem("Select All", new MenuShortcut(KeyEvent.VK_A)));
			// m.addSeparator();
			// m.add(new MenuItem("Find...", new MenuShortcut(KeyEvent.VK_F)));
			// m.add(new MenuItem("Find Next", new MenuShortcut(KeyEvent.VK_G)));
			// m.addActionListener(this);
			// mb.add(m);
			// textPanel.editMenu = m;
			// m = new Menu("Font");
			// m.add(new MenuItem("Make Text Smaller"));
			// m.add(new MenuItem("Make Text Larger"));
			// m.addSeparator();
			// antialiased = new CheckboxMenuItem("Antialiased", Prefs.get(FONT_ANTI, IJ.isMacOSX() ? true : false));
			// antialiased.addItemListener(this);
			// m.add(antialiased);
			// m.add(new MenuItem("Save Settings"));
			// m.addActionListener(this);
			// mb.add(m);
			if (isResultsTable)
			{
				m = new ToolStripMenuItem("Results");
                ToolStripMenuItem ts = new ToolStripMenuItem();

                m.DropDownItems.Add(createSubMenu("Clear Results"));
				m.DropDownItems.Add(createSubMenu("Summarize"));
				m.DropDownItems.Add(createSubMenu("Distribution..."));
				m.DropDownItems.Add(createSubMenu("Set Measurements..."));
				m.DropDownItems.Add(createSubMenu("Sort..."));
				m.DropDownItems.Add(createSubMenu("Plot..."));
				m.DropDownItems.Add(createSubMenu("Options..."));
				// m.DropDownItems.AddActionListener(this);
				mb.Items.Add(m);
			}

			this.Controls.Add(mb);
			// setMenuBar(mb);
		}

        private ToolStripMenuItem createSubMenu(string cmd)
        {
            ToolStripMenuItem sm = new ToolStripMenuItem(cmd);
			sm.Click += MenuItemOnClick;
            return sm;
        }

        private void MenuItemOnClick(object? sender, EventArgs e)
        {
            if (sender is ToolStripMenuItem menuItem)
            {
                actionPerformed(menuItem.Text);
            }
            
        }

        //
		/**
		Adds one or more lines of text to the window.
		@param text		The text to be appended. Multiple
						lines should be separated by \n.
		*/
		public void append(String text)
		{
			textPanel.append(text);
		}
  
		void setFont()
		{
            if (font != null)
            {
                textPanel.Font = font;
            }
            else
            {
                textPanel.Font = new Font(new FontFamily("Arial"), sizes[fontSize]);
			}
            // if (font != null)
            // 	textPanel.setFont(font, antialiased.getState());
            // else
            // 	textPanel.setFont(new Font("SanSerif", Font.PLAIN, sizes[fontSize]), antialiased.getState());
        }
  //
		// boolean openFile(String path)
		// {
		// 	OpenDialog od = new OpenDialog("Open Text File...", path);
		// 	String directory = od.getDirectory();
		// 	String name = od.getFileName();
		// 	if (name == null)
		// 		return false;
		// 	path = directory + name;
  //
		// 	IJ.showStatus("Opening: " + path);
		// 	try
		// 	{
		// 		BufferedReader r = new BufferedReader(new FileReader(directory + name));
		// 		load(r);
		// 		r.close();
		// 	}
		// 	catch (Exception e)
		// 	{
		// 		IJ.error(e.getMessage());
		// 		return true;
		// 	}
		// 	textPanel.setTitle(name);
		// 	setTitle(name);
		// 	IJ.showStatus("");
		// 	return true;
		// }
  //
		/** Returns a reference to this TextWindow's TextPanel. */
		public TextPanel getTextPanel()
		{
			return textPanel;
		}
  
		/** Returns the ResultsTable associated with this TextWindow, or null. */
		public ResultsTable getResultsTable()
		{
			return textPanel != null ? textPanel.getResultsTable() : null;
		}
  //
  //
		// /** Appends the text in the specified file to the end of this TextWindow. */
		// public void load(BufferedReader in)
		// {
		//     int count = 0;
		//     while (true) {
		// 	    string s =in.readLine();
		// 	    if (s==null) break;
		// 	    textPanel.appendLine(s);
		//     }
  //       }
  //
          public void actionPerformed(string cmd)
          {
              if (cmd.Equals("Make Text Larger"))
              {
                  // changeFontSize(true);
              }
              else if (cmd.Equals("Make Text Smaller"))
              {
                  // changeFontSize(false);
              }
              else if (cmd.Equals("Save Settings"))
              {
                  // saveSettings();
              }
              else
		          textPanel.doCommand(cmd);
          }
  //
  //       public void processWindowEvent(WindowEvent e)
  //       {
	 //        super.processWindowEvent(e);
	 //        int id = e.getID();
	 //        if (id == WindowEvent.WINDOW_CLOSING)
		//         close();
	 //        else if (id == WindowEvent.WINDOW_ACTIVATED && !"Log".equals(getTitle()))
		//         WindowManager.setWindow(this);
  //       }
  //
  //       public void itemStateChanged(ItemEvent e)
  //       {
	 //        setFont();
  //       }

          protected override void OnFormClosing(FormClosingEventArgs e)
          {
              close(true);
              base.OnFormClosing(e);
          }

  //       public void close()
  //       {
	 //        close(true);
  //       }
  //
        /** Closes this TextWindow. Display a "save changes" dialog
	        if this is the "Results" window and 'showDialog' is true. */
        public void close(bool showDialog)
        {
	        if (Text.Equals("Results"))
	        {
		        if (showDialog && !Analyzer.resetCounter())
			        return;
		        IJ.setTextPanel(null);
		        // Prefs.saveLocation(LOC_KEY, getLocation());
		        // Dimension d = getSize();
		        // Prefs.set(WIDTH_KEY, d.width);
		        // Prefs.set(HEIGHT_KEY, d.height);
	        }
	        // else if (Text.Equals("Log"))
	        // {
		       //  Prefs.saveLocation(LOG_LOC_KEY, getLocation());
		       //  Dimension d = getSize();
		       //  Prefs.set(LOG_WIDTH_KEY, d.width);
		       //  Prefs.set(LOG_HEIGHT_KEY, d.height);
		       //  IJ.setDebugMode(false);
		       //  IJ.log("\\Closed");
		       //  IJ.notifyEventListeners(IJEventListener.LOG_WINDOW_CLOSED);
	        // }
	        // else if (Text.Equals("Debug"))
	        // {
		       //  Prefs.saveLocation(DEBUG_LOC_KEY, getLocation());
	        // }
	        // else if (textPanel != null && textPanel.rt != null)
	        // {
		       //  if (!saveContents()) return;
	        // }

	        // dispose();
	        // WindowManager.removeWindow(this);
	        // textPanel.flush();
        }
  //
  //       public void rename(String title)
  //       {
	 //        textPanel.rename(title);
  //       }
  //
  //       boolean saveContents()
  //       {
	 //        int lineCount = textPanel.getLineCount();
	 //        if (!textPanel.unsavedLines) lineCount = 0;
	 //        ImageJ ij = IJ.getInstance();
	 //        boolean macro = IJ.macroRunning() || Interpreter.isBatchMode();
	 //        boolean isResults = getTitle().contains("Results");
	 //        if (lineCount > 0 && !macro && ij != null && !ij.quitting() && isResults)
	 //        {
		//         YesNoCancelDialog d = new YesNoCancelDialog(this, getTitle(), "Save " + lineCount + " measurements?");
		//         if (d.cancelPressed())
		// 	        return false;
		//         else if (d.yesPressed())
		//         {
		// 	        if (!textPanel.saveAs(""))
		// 		        return false;
		//         }
	 //        }
	 //        textPanel.rt.reset();
	 //        return true;
  //       }
  //
  //       void changeFontSize(boolean larger)
  //       {
	 //        int in = fontSize;
	 //        if (larger)
	 //        {
		//         fontSize++;
		//         if (fontSize == sizes.length)
		// 	        fontSize = sizes.length - 1;
	 //        }
	 //        else
	 //        {
		//         fontSize--;
		//         if (fontSize < 0)
		// 	        fontSize = 0;
	 //        }
	 //        IJ.showStatus(sizes[fontSize] + " point");
	 //        font = null;
	 //        setFont();
  //       }
  //
  //       public static void setFont(String name, int style, int size)
  //       {
	 //        font = new Font(name, style, size);
  //       }
  //
  //       void saveSettings()
  //       {
	 //        Prefs.set(FONT_SIZE, fontSize);
	 //        Prefs.set(FONT_ANTI, antialiased.getState());
	 //        IJ.showStatus("Font settings saved (size=" + sizes[fontSize] + ", antialiased=" + antialiased.getState() + ")");
  //       }
  //
  //       public void focusGained(FocusEvent e)
  //       {
  //       }
  //
  //       public void focusLost(FocusEvent e) { }

    }
}
